package com.success.task.web.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import com.success.task.web.lucene.core.FolderIndexCreator;

public class StringUtil {

	/**
	 * @param str
	 *            被截取源字符串
	 * @param length
	 *            被截取长度
	 * @return 返回截取后字符串
	 */
	public static String substring(String str, int length) {
		if (null != str) {
			str = deleteSpaceChars(str);
			if (str.length() <= length) {
				return str;
			}
			return str.substring(0, length);
		} else {
			return "";
		}
	}
	
	/**
	 * @param str
	 *            被截取源字符串
	 * @return 返回截取后字符串 默认截取长度为 50
	 */
	public static String substring(String str) {
		return substring(str, 50);
	}

	/**
	 *  去字符两边空格
	 * @param str 要处理的字符串
	 * @return 处理过后字符串
	 */
	public static String deleteSpaceChars(String str) {
		if (str == null) {
			return null;
		}
		String regStartSpace = "^[　 ]*";
		String regEndSpace = "[　 ]*$";
		String strDelSpace = str.replaceAll(regStartSpace, "").replaceAll(
				regEndSpace, "");

		return strDelSpace;
	}
	
	public static String decodeString(String str) {
		if(null == str) {
			return "";
		}
		try {
			return URLDecoder.decode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * @param str
	 * @return
	 * url字符乱码解决方案
	 */
	public static String ensureEncoding(String str) {
		if(null != str) {
			try {
				return decodeString(new String(str.getBytes("ISO-8859-1"),"GBK"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	
	/**
	 * @param str
	 * @return
	 * 默认返回1
	 * 获取页码
	 */
	public static int getInt(String str) {
		if(null == str) {
			return 1;
		}else {
			try {
				return Integer.parseInt(str);
			}catch(Exception e) {
				return 1;
			}
		}
	}
	
	/**
	 * @param str
	 * @return
	 * 删除两边空格
	 * str==null return "";
	 */
	public static String getString(String str) {
		str = deleteSpaceChars(str);
		return str;
	}
	
	/**
	 * @param str
	 * @return
	 * 去掉文件夹目录名
	 */
	public static String deleteFolderName(String str) {
		str = str.replaceAll(FolderIndexCreator.getIndexDirs(), "");
		return str;
	}
	public static void main(String[] args) {
		String stringspace = "%E5%A4%8D%E4%BB%B6%20(10)%20cd.txt";
		System.out.println(StringUtil.ensureEncoding(stringspace));
	}
}
